let logger = require("pomelo-logger").getLogger("pomelo",__filename);
let ObjectID = require('mongodb').ObjectID;

const ORDER_COLLECTION_NAME = "orders";

let OrderDao = function (app) {
    this.app = app;
};

module.exports.create = function (app) {
    let orderDao = new OrderDao(app);
    logger.info("call orderDao.ensureIndex--------------");
    orderDao.ensureIndex(function () {});
    return orderDao;
};

OrderDao.prototype.ensureIndex = function (callback) {
    let dbClient = this.app.get("gameDBClient");
    dbClient.collection(ORDER_COLLECTION_NAME, function(error, collection) {
        if (!!error) {
            logger.error("ensure order error=" + error);
            callback(error);
            return;
        }
        logger.info("begin ensure order--------------");
        collection.ensureIndex({"orderId": 1}, {unique: true}, function (error, result) {
            logger.info("ensure order callback--------------：%s", JSON.stringify(error));
            if (!error) {
                logger.info("ensure order success--------------");
                callback(error);
            }
            callback(error);
            console.dir(result);
        });
    });
};

// 插入订单
OrderDao.prototype.insertOrder = function (order, callback) {
    let dbClient = this.app.get("gameDBClient");
    dbClient.collection(ORDER_COLLECTION_NAME, function (error, collection) {
        if (!!error) {
            logger.error("insert order failed. error=" + error);
            callback(error);
            return;
        }
        collection.insert(order, function (error, document) {
            callback(error);
        });
    });
};